using System;
using System.IO;
using System.Web.Configuration;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;

using MetX;
using MetX.IO;
using MetX.Library;
using MetX.Security;
using MetX.Data;


namespace MetX.Glove.Console
{
	public partial class GloveMain : Form
	{
		public static string InitialXlgsFile;
		public static string InitialCommand;

		public XlgSettings Settings;
		public xlgTokenResolver Resolver;

		private static XlgAppData m_AppData;
		public static XlgAppData AppData
		{
			get
			{
				if (m_AppData == null)
					m_AppData = XlgAppData.Load();
				return m_AppData;
			}
			set
			{
				m_AppData = value;
			}
		}

		public GloveMain()
		{
			InitializeComponent();

		    TinyPosition = new Point( Screen.PrimaryScreen.WorkingArea.Width - (TinySize.Width + 25), 25);
			DiscoverAndLoadTokens();

			if (!string.IsNullOrEmpty(InitialXlgsFile))
			{
				string ixlgs = InitialXlgsFile;
				InitialXlgsFile = null;
				RefreshList(ixlgs);
			}
			if (!string.IsNullOrEmpty(AppData.LastXlgsFile))
			{
				RefreshList(AppData.LastXlgsFile);
			}
			else
				RefreshList();
		}

		public  void DiscoverAndLoadTokens()
		{
			MetX.Security.Crypt.Salt = ASCIIEncoding.ASCII.GetBytes(MetX.Worker.md5(Environment.MachineName + @"\" + Environment.UserDomainName + @"\" + Environment.UserName));
			MetX.Security.Crypt.Reset();

			Resolver = new xlgTokenResolver(this);

			xlgTokenList MachineSpecific = new xlgTokenList("MachineSpecific", xlgTokenListScope.MachineSpecific);
			MachineSpecific.Tokens.Add(new xlgToken(MachineSpecific, "DomainUser", Environment.UserDomainName + @"\" + Environment.UserName));
			MachineSpecific.Tokens.Add(new xlgToken(MachineSpecific, "CurrentDirectory", Environment.CurrentDirectory));
			MachineSpecific.Tokens.Add(new xlgToken(MachineSpecific, "MACHINENAME", Environment.MachineName));
			MachineSpecific.Tokens.Add(new xlgToken(MachineSpecific, "NL", Environment.NewLine));
			MachineSpecific.Tokens.Add(new xlgToken(MachineSpecific, "TAB", "\t"));
			Resolver.TokenListMan.Lists.Add(MachineSpecific);

			string FactoryDefaultsXml = Path.Combine(Environment.CurrentDirectory, "XLG.Factory.Defaults.xlgt");
			string XlgDefaultsXml = Path.Combine(Environment.CurrentDirectory, "XLG.Defaults.xlgt");

			Resolver.TokenListMan.xlgDefaults = LoadDefaults(Resolver, FactoryDefaultsXml, XlgDefaultsXml);
			Resolver.TokenListMan.MyDefaults = LoadMyDefaults(Resolver, XlgDefaultsXml);
		}

		public xlgTokenList LoadDefaults(xlgTokenResolver Resolver, string FactoryDefaultsXml, string XlgDefaultsXml)
		{
			if (!File.Exists(XlgDefaultsXml))
				return LoadAndInitializeTokenList(Resolver, FactoryDefaultsXml, true, XlgDefaultsXml, "XLG.Defaults", xlgTokenListScope.XlgDefaults);
			return LoadAndInitializeTokenList(Resolver, XlgDefaultsXml, false, XlgDefaultsXml, "XLG.Defaults", xlgTokenListScope.XlgDefaults);
		}

		public xlgTokenList LoadMyDefaults(xlgTokenResolver Resolver, string XlgDefaultsXml)
		{
			xlgToken MyDefaultsToken = Resolver.TokenListMan.Find("MyDefaults");
			if (MyDefaultsToken == null)
			{
				MyDefaultsToken = new xlgToken(Resolver.TokenListMan.xlgDefaults, "MyDefaults", null);
				MyDefaultsToken.Default = @"{folder MyDocuments}\My XLG\Tokens\MyDefaults.xlgz";
				Resolver.TokenListMan.xlgDefaults.Tokens.Add(MyDefaultsToken);
				Resolver.ResolveToken(MyDefaultsToken);
				Resolver.TokenListMan.xlgDefaults.SaveFile(XlgDefaultsXml);
			}
			if (MyDefaultsToken != null)
			{
				string MyDefaultsXml = MyDefaultsToken.Value;
				if (!string.IsNullOrEmpty(MyDefaultsXml) && MyDefaultsXml.Contains(@"\"))
				{
					MetX.IO.FileSystem.InsureFolderExists(MyDefaultsXml, true);
					return LoadAndInitializeTokenList(Resolver, MyDefaultsXml, false, MyDefaultsXml, "My.Defaults", xlgTokenListScope.UserDefaults); 
				}
			}
			return null;
		}

		public xlgTokenList LoadAndInitializeTokenList(xlgTokenResolver Resolver, string XlgtFilename, bool ResolveAll, string XlgtFilenameToSaveAsIfAnythingWasResolved, string ID, xlgTokenListScope Scope)
		{
			xlgTokenList ret = null;
			if (File.Exists(XlgtFilename))
			{
				ret = xml.LoadFile<xlgTokenList>(XlgtFilename);
				if (ret != null)
				{
					Resolver.TokenListMan.Lists.Add(ret);
					ret.ID = ID;
					ret.Scope = Scope;
					if (ResolveAll)
					{
						int Count = ret.Resolve(Resolver);
						if (Count > 0 && !string.IsNullOrEmpty(XlgtFilenameToSaveAsIfAnythingWasResolved))
							ret.SaveFile(XlgtFilenameToSaveAsIfAnythingWasResolved);
					}
				}
			}
			return ret;
		}


		private void buttonGo_Click(object sender, EventArgs e)
		{
			Enabled = false;
			try
			{
				UpdateItem();
				this.Text = "XLG: Gen Time...";
				Settings.Generate(this);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
			finally
			{
				Enabled = true;
				this.Text = "XLG";
			}
		}

		private string ChooseFile(string Default, string Ext)
		{
			openFileDialog1.FileName = Default;
			openFileDialog1.AddExtension = true;
			openFileDialog1.CheckFileExists = true;
			openFileDialog1.CheckPathExists = true;
			openFileDialog1.DefaultExt = "." + Ext;
			openFileDialog1.Filter = "*." + Ext + "|*." + Ext;
			openFileDialog1.Multiselect = false;
			openFileDialog1.ShowDialog(this);
			if (openFileDialog1.FileName != null)
				return openFileDialog1.FileName;
			return Default;
		}

		private void buttonChooseXlgFile_Click(object sender, EventArgs e)
		{
			textXlgFile.Text = ChooseFile(textXlgFile.Text, "xlg");
		}

		private void buttonChooseXlgFileXsl_Click(object sender, EventArgs e)
		{
			openFileDialog1.FileName = XlgXslFilename;
			openFileDialog1.AddExtension = true;
			openFileDialog1.CheckFileExists = true;
			openFileDialog1.CheckPathExists = true;
			openFileDialog1.DefaultExt = ".xlg.xsl";
			openFileDialog1.Filter = "*.xlg.xsl|*.xlg.xsl";
			openFileDialog1.Multiselect = false;
			openFileDialog1.ShowDialog(this);
			if (openFileDialog1.FileName != null)
				XlgXslFilename = openFileDialog1.FileName;
		}

		private void buttonChooseOutput_Click(object sender, EventArgs e)
		{
			saveFileDialog1.FileName = OutputFilename;
			saveFileDialog1.AddExtension = false;
			saveFileDialog1.CheckFileExists = false;
			saveFileDialog1.CheckPathExists = true;
			saveFileDialog1.DefaultExt = ".cs";
			saveFileDialog1.Filter = "*.*|*.*|*.cs|*.cs|*.vb|*.vb|*.xml|*.xml";
			saveFileDialog1.ShowDialog(this);
			if (saveFileDialog1.FileName != null)
				OutputFilename = saveFileDialog1.FileName;
		}

		private void buttonRegen_Click(object sender, EventArgs e)
		{
			if (InvokeRequired)
			{
				Invoke(new EventHandler(buttonRegen_Click), new object[] { sender, e });
				return;
			}

			Enabled = false;
			try
			{
				this.Text = "XLG: Regenerating...";
				Settings.Regenerate(this);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
			finally
			{
				this.Text = "XLG";
				Enabled = true;
			}
		}
		private bool RefreshingList;
		private void RefreshList()
		{
			if (Settings != null && !string.IsNullOrEmpty(Settings.Filename))
				RefreshList(Settings.Filename);
			else
				RefreshList(null);
		}
		private void RefreshList(string xlgSourceFilename)
		{
			if (RefreshingList || (string.IsNullOrEmpty(xlgSourceFilename) && Settings == null))
				return;

			if (RefreshingList) return;
			RefreshingList = true;
			try
			{
				if (string.IsNullOrEmpty(xlgSourceFilename) && Settings != null)
				{
					MetadataSources.Items.Clear();
					foreach (xlgSource currentSource in Settings.Sources)
					{
						ListViewItem lvi = new ListViewItem(currentSource.DisplayName);
						lvi.Tag = currentSource;
						lvi.Checked = currentSource.Selected;
						MetadataSources.Items.Add(lvi);
					}
				}
				else if (File.Exists(xlgSourceFilename))
				{
					Settings = XlgSettings.Load(xlgSourceFilename);
					Settings.Filename = xlgSourceFilename;
					Settings.GUI = this;
					MetadataSources.Items.Clear();

					if (Settings.TokenList == null || Settings.TokenList.Tokens.Count == 0)
						Settings.TokenList = new xlgTokenList();
					Resolver.TokenListMan.Lists.Add(Settings.TokenList);

					foreach (xlgSource currentSource in Settings.Sources)
					{
						ListViewItem lvi = new ListViewItem(currentSource.DisplayName);
						lvi.Tag = currentSource;
						lvi.Checked = currentSource.Selected;
						MetadataSources.Items.Add(lvi);
					}

					if (Settings.Filename != AppData.LastXlgsFile)
					{
						AppData.LastXlgsFile = Settings.Filename;
						AppData.Save();
					}

					if (MetadataSources.Items.Count > 0)
						MetadataSources.Items[MetadataSources.Items.Count - 1].Selected = true;
				}
                else if (!xlgSourceFilename.ToLower().Contains("default."))
					MessageBox.Show(xlgSourceFilename + " does not exist.");
			}
			finally { RefreshingList = false; }
		}

		private void button1_Click(object sender, EventArgs e)
		{
			string toParse = Clipboard.GetText();
			StringBuilder sb = new StringBuilder();
			string[] lines = toParse.Replace("\r", string.Empty).Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string CurrLine in lines)
			{
				if (CurrLine.IndexOf(" = ") > -1)
				{
					string s = Token.First(CurrLine, ";");
					string b = Token.First(s, " = ");
					int spaces = b.Length - b.Trim().Length;
					sb.AppendLine(new string(' ', spaces) + Token.After(s, 1, " = ") + " = " + b.Trim() + ";");
				}
				else
					sb.AppendLine(CurrLine);
			}
			Clipboard.Clear();
			Clipboard.SetText(sb.ToString());
		}

		private void GloveMain_Load(object sender, EventArgs e)
		{
			MetadataSources.Focus();
			if (MetadataSources.Items.Count > 0)
				MetadataSources.SelectedIndices.Add(0);
			NormalSplitterDistance = splitContainer1.SplitterDistance;
			NormalPosition = new Point(this.Location.X, this.Location.Y);
			NormalSize = new Size(this.Size.Width, this.Size.Height);

			guiSizeStripMenuItemNormal_Click(null, null);
		}

		private void GloveMain_FormClosing(object sender, FormClosingEventArgs e)
		{
		}

		bool AutoGenActive = false;
		List<FileSystemWatcher> FSWs;

		private object SyncRoot = new object();


		private void buttonAutoGen_Click(object sender, EventArgs e)
		{
			lock (SyncRoot)
			{
				if (FSWs != null)
				{
					while (FSWs != null && FSWs.Count > 0)
					{
						FileSystemWatcher FSW = FSWs[FSWs.Count - 1];
						FSWs.Remove(FSW);
						FSW.EnableRaisingEvents = false;
						FSW.Dispose();
						FSW = null;
					}
					FSWs = null;
					autoRegenToolbarButton.Image = global::XLG.Pipeline.Properties.Resources.circle_blue;
					autoRegenOnChangedXSLToolStripMenuItem.Image = global::XLG.Pipeline.Properties.Resources.circle_blue;
				}
				else
				{
					FSWs = new List<FileSystemWatcher>();
					FileSystemWatcher FSW = new FileSystemWatcher(GloveMain.AppData.SupportPath);
					FSW.Changed += new FileSystemEventHandler(FSW_Changed);
					FSW.Created += new FileSystemEventHandler(FSW_Changed);
					FSW.Deleted += new FileSystemEventHandler(FSW_Changed);
					FSW.Error += new ErrorEventHandler(FSW_Error);
					FSW.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
					FSW.EnableRaisingEvents = true;
					FSWs.Add(FSW);

                    if (CurrSource != null && CurrSource.XslPath.IsNotEmpty())
				    {
				        FSW = new FileSystemWatcher(CurrSource.XslPath);
				        FSW.Changed += new FileSystemEventHandler(FSW_Changed);
				        FSW.Created += new FileSystemEventHandler(FSW_Changed);
				        FSW.Deleted += new FileSystemEventHandler(FSW_Changed);
				        FSW.Error += new ErrorEventHandler(FSW_Error);
				        FSW.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
				        FSW.EnableRaisingEvents = true;
				        FSWs.Add(FSW);
				    }
				    autoRegenToolbarButton.Image = global::XLG.Pipeline.Properties.Resources.circle_green;
					autoRegenOnChangedXSLToolStripMenuItem.Image = global::XLG.Pipeline.Properties.Resources.circle_green;
				}
				toolStrip1.Invalidate();
				toolStrip1.Refresh();
			}
			if (FSWs != null)
				guiSizeStripMenuItemTinyOnTop_Click(null, null);
			else
				guiSizeStripMenuItemNormal_Click(null, null);
		}

		void FSW_Error(object sender, ErrorEventArgs e)
		{
			MessageBox.Show(e.GetException().ToString());
		}

		void FSW_Changed(object sender, FileSystemEventArgs e)
		{
			if (e.FullPath.IndexOf(".xlg.xsl") > 0)
			{
				if (System.Threading.Monitor.TryEnter(SyncRoot))
				{
					try
					{
						if (AutoGenActive)
							return;
						AutoGenActive = true;
						Invoke(new MethodInvoker(SynchAutoRegen));
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.ToString());
					}
					finally
					{
						StartWatchingFolders();
						AutoGenActive = false;
						System.Threading.Monitor.Exit(SyncRoot);
					}
				}
			}
		}

		public void StopWatchingFolders()
		{
			if (FSWs == null || FSWs.Count == 0)
				return;
			try
			{
				for (int i = 0; FSWs != null && i < FSWs.Count; i++)
				{
					FSWs[i].EnableRaisingEvents = false;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}

		public void StartWatchingFolders()
		{
			if (FSWs == null || FSWs.Count == 0)
				return;
			try
			{
				for (int i = 0; FSWs != null && i < FSWs.Count; i++)
				{
					FSWs[i].EnableRaisingEvents = true;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}

		void SynchAutoRegen()
		{
			autoRegenToolbarButton.Image = global::XLG.Pipeline.Properties.Resources.circle_orange;
			autoRegenOnChangedXSLToolStripMenuItem.Image = global::XLG.Pipeline.Properties.Resources.circle_orange;

			StopWatchingFolders();

			buttonRegen_Click(null, null);
			autoRegenToolbarButton.Image = global::XLG.Pipeline.Properties.Resources.circle_green;
			autoRegenOnChangedXSLToolStripMenuItem.Image = global::XLG.Pipeline.Properties.Resources.circle_green;
		}

		private void MetadataSources_ItemChecked(object sender, ItemCheckedEventArgs e)
		{
			((xlgSource)e.Item.Tag).Selected = e.Item.Checked;
		}

		public xlgSource CurrSource = null;

		private void MetadataSources_SelectedIndexChanged(object sender, EventArgs e)
		{
			UpdateItem();
			if (MetadataSources.SelectedItems.Count > 0)
			{
				CurrSource = (xlgSource)MetadataSources.SelectedItems[0].Tag;
				textAppXlgXsl.Text = CurrSource.XslFilename;
				textOutput.Text = CurrSource.OutputFilename;
				textOutputXml.Text = CurrSource.OutputXml;
				textXlgFile.Text = CurrSource.XlgDocFilename;
				textConnectionName.Text = CurrSource.DisplayName;
				textConnectionStringName.Text = CurrSource.ConnectionName;
				textConnectionString.Text = CurrSource.ConnectionString;
				textSqlToXml.Text = CurrSource.SqlToXml;
				checkRegenerateOnly.Checked = CurrSource.RegenerateOnly;
				int index = comboProviderName.FindString(CurrSource.ProviderName);
				if (index > -1)
					comboProviderName.SelectedIndex = index;
			}
		}

		public void UpdateItem()
		{
			if (CurrSource != null)
			{
				CurrSource.XslFilename = textAppXlgXsl.Text;
				CurrSource.OutputFilename = textOutput.Text;
				CurrSource.OutputXml = textOutputXml.Text;
				CurrSource.XlgDocFilename = textXlgFile.Text;
				CurrSource.DisplayName = textConnectionName.Text;
				CurrSource.ConnectionName = textConnectionStringName.Text;
				CurrSource.ConnectionString = textConnectionString.Text;
				CurrSource.RegenerateOnly = checkRegenerateOnly.Checked;
				CurrSource.SqlToXml = textSqlToXml.Text;
				if (comboProviderName.SelectedIndex > -1)
					CurrSource.ProviderName = (string)comboProviderName.SelectedItem;
			}
		}

		private void buttonSave_Click(object sender, EventArgs e)
		{
			UpdateItem();
			Settings.Save();
			AppData.LastXlgsFile = Settings.Filename;
			AppData.Save();
			if (sender != null)
				RefreshList();
		}

		private void buttonLoad_Click(object sender, EventArgs e)
		{
			openFileDialog1.FileName = (Settings != null && !string.IsNullOrEmpty(Settings.Filename) ? Settings.Filename : string.Empty);
			if (string.IsNullOrEmpty(openFileDialog1.FileName) && Directory.Exists(AppData.SupportPath))
				openFileDialog1.InitialDirectory = AppData.SupportPath;
			openFileDialog1.AddExtension = true;
			openFileDialog1.CheckFileExists = true;
			openFileDialog1.CheckPathExists = true;
			openFileDialog1.DefaultExt = ".xlgs";
			openFileDialog1.Filter = "*.xlgs|*.xlgs";
			openFileDialog1.Multiselect = false;
			openFileDialog1.ShowDialog(this);
			if (openFileDialog1.FileName != null)
			{
				RefreshList(openFileDialog1.FileName);
			}
		}

		private void buttonAdd_Click(object sender, EventArgs e)
		{
			string ItemName = Microsoft.VisualBasic.Interaction.InputBox("What is the name of the database you wish to walk?", "DATABASE NAME", "CLONE", -1, -1);
			if (!string.IsNullOrEmpty(ItemName))
			{
				if (CurrSource == null && Settings.Sources.Count > 0)
					CurrSource = Settings.Sources[0];

				xlgSource NewSource = null;
				if (ItemName == "CLONE")
				{
					NewSource = xml.FromXml<xlgSource>(xml.ToXml<xlgSource>(CurrSource, false));
				}
				else
				{
					NewSource = new xlgSource(AppData.BasePath, AppData.ParentNamespace, Token.Last((CurrSource != null ? CurrSource.ProviderName : (Settings.Sources.Count + 1).ToString()), ".") + ": " + ItemName, ItemName);

					if (CurrSource != null)
						NewSource.BasePath = Token.Before(CurrSource.OutputFilename, Token.Count(CurrSource.OutputFilename, @"\") - 1, @"\") + @"\" + ItemName + @"\";
					else
						NewSource.BasePath = AppData.BasePath + ItemName + @"\";
					IO.FileSystem.InsureFolderExists(NewSource.BasePath, false);
					// NewSource.ConfigFilename = CurrSource.ConfigFilename;

					if (CurrSource != null)
					{
						NewSource.ConnectionString = CurrSource.ConnectionString;
						NewSource.OutputFilename = NewSource.BasePath + ItemName + ".Glove." + Path.GetExtension(CurrSource.OutputFilename);
						NewSource.OutputXml = NewSource.BasePath + ItemName + ".Glove.xml";
						NewSource.ProviderName = CurrSource.ProviderName;
						NewSource.Selected = true;
						NewSource.XlgDocFilename = NewSource.BasePath + ItemName + ".xlgd";
						NewSource.XslFilename = CurrSource.XslFilename;
					}
					else
					{
						NewSource.OutputFilename = NewSource.BasePath + ItemName + ".Glove.cs";
						NewSource.OutputXml = NewSource.BasePath + ItemName + ".Glove.xml";
						NewSource.ProviderName = "System.Data.SqlClient";
						NewSource.Selected = true;
						NewSource.XlgDocFilename = NewSource.BasePath + ItemName + ".xlgd";
						NewSource.XslFilename = AppData.SupportPath + "CSharp DAL.xlg.xsl";
					}
				}

				//if (ItemName != "CLONE")
				//    foreach (xlgSource CurrItem in Settings.Sources)
				//        CurrItem.Selected = false;

				NewSource.Selected = true;
				Settings.Sources.Add(NewSource);
				buttonSave_Click(null, null);
				RefreshList();
				MetadataSources.Items[MetadataSources.Items.Count - 1].Selected = true;
			}
		}

		private void buttonDelete_Click(object sender, EventArgs e)
		{
			if (CurrSource != null)
			{
				if (MessageBox.Show("Are you sure you want to remove the current step?\r\n\tThere is no undo for this action.", "REMOVE STEP", MessageBoxButtons.YesNo) == DialogResult.Yes)
				{
					Settings.Sources.Remove(CurrSource);
					CurrSource = null;
					buttonSave_Click(null, null);
					RefreshList();
				}
			}
		}

		[XmlIgnore]
		public string XlgFilename
		{
			get
			{
				return textXlgFile.Text.Replace("{~}", CurrSource.BasePath);
			}
			set
			{
				if (value != null && CurrSource.BasePath != null && value.StartsWith(CurrSource.BasePath))
					textXlgFile.Text = Path.Combine(CurrSource.BasePath, value.Substring(CurrSource.BasePath.Length));
				else
					textXlgFile.Text = value;
			}
		}

		[XmlIgnore]
		public string XlgXslFilename
		{
			get
			{
				return textAppXlgXsl.Text.Replace("{~}", CurrSource.BasePath);
			}
			set
			{
				if (value != null && CurrSource.BasePath != null && value.StartsWith(CurrSource.BasePath))
					textAppXlgXsl.Text = Path.Combine(CurrSource.BasePath, value.Substring(CurrSource.BasePath.Length));
				else
					textAppXlgXsl.Text = value;
			}
		}

		[XmlIgnore]
		public string OutputXmlFilename
		{
			get
			{
				return textOutputXml.Text.Replace("{~}", CurrSource.BasePath);
			}
			set
			{
				if (value != null && CurrSource.BasePath != null && value.StartsWith(CurrSource.BasePath))
					textOutputXml.Text = Path.Combine(CurrSource.BasePath, value.Substring(CurrSource.BasePath.Length));
				else
					textOutputXml.Text = value;
			}
		}

		[XmlIgnore]
		public string OutputFilename
		{
			get
			{
				return textOutput.Text.Replace("{~}", CurrSource.BasePath);
			}
			set
			{
				if (value != null && CurrSource.BasePath != null && value.StartsWith(CurrSource.BasePath))
					textOutput.Text = Path.Combine(CurrSource.BasePath, value.Substring(CurrSource.BasePath.Length));
				else
					textOutput.Text = value;
			}
		}

		private void buttonEditXlgFile_Click(object sender, EventArgs e)
		{
			IO.FileSystem.InsureFolderExists(XlgFilename, true);
			if (!File.Exists(XlgFilename))
			{
				File.WriteAllText(XlgFilename, MetX.Data.DefaultXlg.xml.Replace("[Default]", textConnectionStringName.Text));
			}
			Edit(XlgFilename);
		}

		private void buttonEditXlgXslFile_Click(object sender, EventArgs e)
		{
			IO.FileSystem.InsureFolderExists(XlgXslFilename, true);
            Edit(XlgXslFilename);
		}

        /*
        private void buttonEditConfigFile_Click(object sender, EventArgs e)
        {
            IO.FileSystem.InsureFolderExists(textSettings.Text, true);
            Edit(textSettings.Text);
        }
        */

        private void buttonViewOutputFolder_Click(object sender, EventArgs e)
		{
			FileSystem.InsureFolderExists(OutputFilename, true);
            Edit(OutputFilename);
		}

	    private void Edit(string filename)
	    {
	        try
	        {
	            if (File.Exists(AppData.TextEditor))
	                Process.Start(AppData.TextEditor, filename);
	            else
	                Process.Start("notepad", filename);
	        }
	        catch (Exception ex)
	        {
	            MessageBox.Show(this, ex.ToString());
	        }
	    }

		private void buttonViewtextOutputXml_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(textOutputXml.Text))
				OutputXmlFilename = OutputFilename.Substring(0, OutputFilename.Length - Path.GetExtension(OutputFilename).Length) + ".xml";
			IO.FileSystem.InsureFolderExists(OutputXmlFilename, true);
            Edit(OutputXmlFilename);
		}

		private void buttonChoosetextOutputXml_Click(object sender, EventArgs e)
		{
			saveFileDialog1.FileName = OutputXmlFilename;
			saveFileDialog1.AddExtension = false;
			saveFileDialog1.CheckFileExists = false;
			saveFileDialog1.CheckPathExists = true;
			saveFileDialog1.DefaultExt = ".xml";
			saveFileDialog1.Filter = "*.*|*.*|*.xml|*.xml";
			saveFileDialog1.ShowDialog(this);
			if (saveFileDialog1.FileName != null)
				OutputXmlFilename = saveFileDialog1.FileName;
		}

		private void newToolStripMenuItem_Click(object sender, EventArgs e)
		{
			XlgSettings t = Settings;
			Settings = new XlgSettings(this);
			Settings.Sources = new List<xlgSource>();
			Settings.DefaultConnectionString = t.DefaultConnectionString;
			Settings.DefaultProviderName = t.DefaultProviderName;

			saveFileDialog1.FileName = string.Empty;
			saveFileDialog1.AddExtension = true;
			saveFileDialog1.CheckFileExists = false;
			saveFileDialog1.CheckPathExists = true;
			saveFileDialog1.DefaultExt = ".xlgs";
			saveFileDialog1.Filter = "*.xlgs|*.xlgs";
			saveFileDialog1.ShowDialog(this);
			if (!string.IsNullOrEmpty(saveFileDialog1.FileName) && !File.Exists(saveFileDialog1.FileName))
			{
				Settings.Filename = saveFileDialog1.FileName;
				buttonSave_Click(null, null);
				RefreshList();
			}
		}

		private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			saveFileDialog1.FileName = Settings.Filename;
			saveFileDialog1.AddExtension = true;
			saveFileDialog1.CheckFileExists = false;
			saveFileDialog1.CheckPathExists = true;
			saveFileDialog1.DefaultExt = ".xlgs";
			saveFileDialog1.Filter = "*.xlgs|*.xlgs";
			saveFileDialog1.ShowDialog(this);
			if (!string.IsNullOrEmpty(saveFileDialog1.FileName))
			{
				Settings.Filename = saveFileDialog1.FileName;
				buttonSave_Click(null, null);
			}
		}

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			buttonSave_Click(null, null);
			Close();
		}

		private void generateSelectedToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void regenerateSelectedToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void buttonEditConnectionString_Click(object sender, EventArgs e)
		{
			/*
			try
			{
				object[] args = new object[] { };
				System.Type linkType = System.Type.GetTypeFromProgID("DataLinks");
				object linkObj = Activator.CreateInstance(linkType);
				object connObj = linkType.InvokeMember("PromptNew", System.Reflection.BindingFlags.InvokeMethod, null, linkObj, args);
				if(connObj != null)
				{
					string connString = connObj.GetType().InvokeMember("ConnectionString", System.Reflection.BindingFlags.GetProperty, null, connObj, args).ToString();
					if(!string.IsNullOrEmpty(connString))
					{
						textConnectionString.Text = connString;
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
            
			DataConnectionDialog dcd = null;
			try
			{
				dcd = new DataConnectionDialog();
				DataSource.AddStandardDataSources(dcd);
				/*
				if (!string.IsNullOrEmpty(textConnectionString.Text))
				{
					dcd.ConnectionString = textConnectionString.Text;
					dcd.SelectedDataProvider = Microsoft.Data.ConnectionUI.DataProvider.SqlDataProvider;
				}
				* /
				if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
				{
					textConnectionString.Text = dcd.ConnectionString;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
			finally
			{
				if (dcd != null)
					dcd.Dispose();
			}
			*/

		}

		private void loadStripButton_Click(object sender, EventArgs e)
		{
			buttonLoad_Click(null, null);
		}

		public enum GuiSize
		{
			Normal,
			TinyOnTop,
			Tiny
		}

		public Size NormalSize = new Size(850, 550);
		public Point NormalPosition = new Point(0, 0);
		public int NormalSplitterDistance = 200;

		public Size TinySize = new Size(370, 67);
		//public Point TinyPosition = new Point(2880, 25);

        //public Size TinySize = new Size(0, 0);
        public Point TinyPosition = new Point(0, 0);

		public GuiSize CurrentSize = GuiSize.Normal;


		private void guiSizeStripMenuItemNormal_Click(object sender, EventArgs e)
		{
			try
			{
				lock (SyncRoot)
				{
					if (CurrentSize != GuiSize.Normal)
					{
						TinyPosition = new Point(this.Location.X, this.Location.Y);
						TinySize = new Size(this.Size.Width, this.Size.Height);

						Location = NormalPosition;
						Size = NormalSize;
						splitContainer1.SplitterDistance = NormalSplitterDistance;
						CurrentSize = GuiSize.Normal;
						TopMost = false;

						guiSizeStripMenuItemNormal.Checked = true;
						guiSizeStripMenuItemTiny.Checked = false;
						guiSizeStripMenuItemTinyOnTop.Checked = false;
						toggleGuiStripSplitButton.Text = guiSizeStripMenuItemNormal.Text;
					}
				}
			}
			catch { }
		}

		private void guiSizeStripMenuItemTinyOnTop_Click(object sender, EventArgs e)
		{
			try
			{
				guiSizeStripMenuItemTiny_Click(sender, e);
				TopMost = true;

				guiSizeStripMenuItemNormal.Checked = false;
				guiSizeStripMenuItemTiny.Checked = false;
				guiSizeStripMenuItemTinyOnTop.Checked = true;
				toggleGuiStripSplitButton.Text = "Tiny";
			}
			catch { }
		}

		private void guiSizeStripMenuItemTiny_Click(object sender, EventArgs e)
		{
			try
			{
				lock (SyncRoot)
				{
					guiSizeStripMenuItemNormal.Checked = false;
					guiSizeStripMenuItemTiny.Checked = true;
					guiSizeStripMenuItemTinyOnTop.Checked = false;

					if (CurrentSize != GuiSize.TinyOnTop)
					{
						if (CurrentSize == GuiSize.Normal)
						{
							NormalSplitterDistance = splitContainer1.SplitterDistance;
							NormalPosition = new Point(this.Location.X, this.Location.Y);
							NormalSize = new Size(this.Size.Width, this.Size.Height);
						}
						Location = TinyPosition;
						Size = TinySize;
						splitContainer1.SplitterDistance = 45;
						CurrentSize = GuiSize.TinyOnTop;
						TopMost = false;
						toggleGuiStripSplitButton.Text = guiSizeStripMenuItemTiny.Text;
					}
				}
			}
			catch { }
		}

		private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
		{

		}

		private void toggleGuiStripSplitButton_ButtonClick(object sender, EventArgs e)
		{
			if (guiSizeStripMenuItemNormal.Checked)
				guiSizeStripMenuItemTinyOnTop_Click(null, null);
			else if (guiSizeStripMenuItemTinyOnTop.Checked)
				//				guiSizeStripMenuItemTiny_Click(null, null);
				//			else
				guiSizeStripMenuItemNormal_Click(null, null);

		}

		private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
		{

		}

		private void tableLayoutPanel4_Paint(object sender, PaintEventArgs e)
		{
					}

		private void buttonCleanup_Click(object sender, EventArgs e)
		{

		}
	}
}
